<!--
 * @Author: quit
 * @Date: 2021-12-08 10:37:09
 * @LastEditTime: 2022-01-14 17:07:17
 * @Descripttion: 设备管理
-->
<template>
    <div id="DeviceManagement">
        <div class="app-container" style="height: 100%">
            <el-row :gutter="5">
                <!-- 左侧 -->
                <el-col :span="4" class="left">
                    <el-card>
                        <div v-loading="treeLoading" class="item-box">
                            <el-input v-model="filterText" class="tree-search" placeholder="输入关键字进行过滤" />
                            <el-tree ref="tree" :data="treeData" :props="defaultProps" :filter-node-method="filterNode" @node-click="handleNodeClick" />
                        </div>
                    </el-card>
                </el-col>
                <!-- 右侧 -->
                <el-col :span="20" class="right">
                    <el-card>
                        <el-row class="right-container">
                            <el-col>
                                <el-divider content-position="left">搜索信息</el-divider>
                                <div class="search">
                                    <el-form :inline="true" :model="searchFrom">
                                        <el-form-item :label="'类型'">
                                            <el-input v-model="searchFrom.subsysname" disabled :placeholder="'请选择类型名'" />
                                        </el-form-item>
                                        <el-form-item :label="'设备名'">
                                            <el-input v-model="searchFrom.drname" :placeholder="'请输入设备名'" />
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" icon="el-icon-zoom-in" @click="getDeviceList">{{ $t('button.search') }}</el-button>
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-col>
                            <el-col class="btns">
                                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemsBtn">{{ '添加设备' }}</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
                            </el-col>
                            <el-col>
                                <el-table
                                    ref="table"
                                    v-loading="loading"
                                    :max-height="maxHeight"
                                    :data="tableData"
                                    :empty-text="$t('table.emptyText')"
                                    style="width: 100%"
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column type="selection" min-width="40" fixed="left" />
                                    <el-table-column prop="drid" label="ID" min-width="70" fixed="left" />
                                    <el-table-column prop="appid" :label="'项目ID'" min-width="80" fixed="left" />
                                    <el-table-column prop="drname" :label="'设备名'" min-width="150" />
                                    <el-table-column prop="subsystemid" :label="'系统ID'" min-width="70" />
                                    <!-- 关联显示 Todo -->
                                    <el-table-column :label="'子系统'" min-width="140">
                                        <template slot-scope="scope">
                                            {{
                                                typeData &&
                                                    typeData.find(item => {
                                                        return item.value == scope.row.subsystemid
                                                    }).label
                                            }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="dricon" :label="'系统icon'" min-width="140" />
                                    <el-table-column header-align="center" align="center" prop="drtype" :label="'特殊类型'" min-width="80" />
                                    <el-table-column header-align="center" align="center" prop="drno" :label="'特殊编码'" min-width="80" />
                                    <el-table-column header-align="center" align="center" prop="assetsid" :label="'资产编号'" min-width="80" />
                                    <el-table-column header-align="center" align="center" prop="drposition" :label="'位置'" min-width="100" />
                                    <el-table-column prop="dractivetype" :label="'按钮动作'" min-width="100">
                                        <template slot-scope="scope">{{ scope.row.dractivetype.join(',') }}</template>
                                    </el-table-column>
                                    <el-table-column prop="spdrid" :label="'视频ID'" min-width="80" />
                                    <el-table-column prop="drqrcode" :label="'二维码'" min-width="100" />
                                    <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="160">
                                        <template slot-scope="scope">
                                            <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                                            <el-button type="danger" size="mini" @click="handleDetele(scope.row)">{{ $t('button.delete') }}</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <!-- 分页 -->
                                <el-pagination
                                    :current-page="pages.page"
                                    :page-sizes="[1, 5, 10, 15]"
                                    :page-size="pages.size"
                                    layout="prev, pager, next, total, sizes, jumper"
                                    :total="pages.total"
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                />
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <!-- 添加\修改弹出层 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" @close="addDialogClose">
            <div class="add-dialog-container">
                <el-form ref="addFrom" :model="addDialogForm" label-width="90px">
                    <el-form-item label="类型">
                        <el-input v-model="searchFrom.subsysname" disabled />
                    </el-form-item>
                    <el-form-item label="设备名">
                        <el-input v-model="addDialogForm.drname" placeholder="请输入设备名" />
                    </el-form-item>
                    <el-form-item label="设备二维码">
                        <el-input v-model="addDialogForm.drqrcode" placeholder="请输入设备二维码" />
                    </el-form-item>
                    <el-form-item label="特殊类型">
                        <el-select v-model="addDialogForm.drtype" placeholder="请选择条件类型" clearable>
                            <el-option v-for="(item, index) in andorData" :key="index" :label="item.typename" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="特殊编码">
                        <el-input v-model="addDialogForm.drno" placeholder="请输入特殊编码" />
                    </el-form-item>
                    <el-form-item label="资产ID">
                        <el-select v-model="addDialogForm.assetsid" placeholder="请选择条件类型" clearable>
                            <el-option v-for="(item, index) in assetsData" :key="index" :label="item.assetsname" :value="item.assetsid" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="安装位置">
                        <!-- <el-autocomplete v-model="addDialogForm.drposition" popper-class="my-autocomplete" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect">
              <i slot="suffix" class="el-icon-edit el-input__icon" @click="handleIconClick" />
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }}</div>
                <span class="addr">{{ item.address }}</span>
              </template>
            </el-autocomplete> -->
                        <el-select v-model="addDialogForm.drposition" placeholder="请选择条件类型" clearable>
                            <el-option v-for="(item, index) in drpositionData" :key="index" :label="item.buildname" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备描述">
                        <el-input v-model="searchFrom.drdescribe" placeholder="请输入设备描述" />
                    </el-form-item>
                    <el-form-item label="关联视频">
                        <el-select v-model="addDialogForm.spdrid" placeholder="请选择条件类型" clearable>
                            <el-option v-for="(item, index) in spdridData" :key="index" :label="item.drname" :value="item.drid" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="点击动作">
                        <el-checkbox-group v-model="addDialogForm.dractivetype" class="checkbox">
                            <el-checkbox v-for="(item, index) in checkboxData" :key="index" :label="item.id" name="type">{{ item.label }}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button v-if="addDialogState === 0" type="primary" @click="sendAddItem">确 定</el-button>
                <el-button v-if="addDialogState === 1" type="primary" @click="sendEditItem">提 交</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import $ from 'jquery'
import { getData } from '@/utils/auth'
import {
    getDeviceList,
    getSpecialList,
    getVideoList,
    getAssetsTypeList,
    getBYIdAllList,
    addDeviceItem,
    editDevicedelete,
    deleteDeviceItem,
    deleteDeviceItems
} from '@/api/BotRequest'
import { getSubSysInfo, getSubSysName } from '@/api/BmRequest'

export default {
    components: {},
    data() {
        return {
            botData: {},
            treeData: [],
            typeData: [],
            filterText: '',
            treeLoading: false,
            defaultProps: {
                children: 'children',
                label: 'subsysname'
            },
            searchFrom: {
                appid: null,
                drname: null,
                drtype: null, // Todo ?
                subsystemid: null,
                subsysname: null
            },
            maxHeight: null,
            loading: false,
            isCheckedArr: [],
            tableData: [],
            pages: {
                page: 1,
                size: 10,
                total: 0
            },
            dialogTitle: '',
            addDialogState: null,
            dialogVisible: false,
            addDialogForm: {
                drid: null,
                appid: null,
                drname: null,
                subsystemid: null,
                dricon: null,
                drtype: null,
                drno: null,
                assetsid: null,
                drdescribe: null,
                drposition: null,
                dractivetype: [],
                spdrid: null,
                drqrcode: null
            },
            andorData: [],
            spdridData: [],
            assetsData: [],
            drpositionData: [],
            checkboxData: [
                { id: 1, label: '设备信息' },
                { id: 2, label: '设备结构图' },
                { id: 3, label: '打开视频' },
                { id: 4, label: '打开记录' },
                { id: 5, label: '设备资产信息' },
                { id: 6, label: '设备报警' },
                { id: 7, label: '打开门禁记录' }
            ]
        }
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val)
        }
    },
    created() {
        this.botData = getData('BotData')
        this.getDeviceList()
        this.getSubSysInfo()
        this.getSpecialList()
        this.getVideoList()
        this.getAssetsTypeList()
        this.getBYIdAllList()
        this.getSubSysName()
    }, // 生命周期 - 创建完成（可以访问当前this实例）
    mounted() {
        this.setTableHeight()
        window.onresize = () => {
            this.setTableHeight()
        }
    }, // 生命周期 - 挂载完成（可以访问DOM元素）
    beforeCreate() {}, // 生命周期 - 创建之前
    beforeMount() {}, // 生命周期 - 挂载之前
    beforeUpdate() {}, // 生命周期 - 更新之前
    updated() {}, // 生命周期 - 更新之后
    beforeDestroy() {}, // 生命周期 - 销毁之前
    destroyed() {}, // 生命周期 - 销毁完成
    activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
    // 方法集合
    methods: {
        // 动态设置表格高
        setTableHeight() {
            let num = $('.right-container').height() - 203
            this.maxHeight = num
        },
        async getSubSysName() {
            const { data } = await getSubSysName()
            this.typeData = data
        },
        /* 左侧树形数据操作 */
        // 获取类型列表
        async getSubSysInfo() {
            this.treeLoading = true
            try {
                const { data } = await getSubSysInfo()
                this.treeData = data
            } catch (error) {
                console.log(error)
            } finally {
                this.treeLoading = false
            }
        },
        // 搜索事件
        filterNode(value, data) {
            if (!value) return true
            if (data.children) return false
            return data.subsysname.indexOf(value) !== -1
        },
        // 节点点击事件
        handleNodeClick(data) {
            if (data.subsysparent !== -1) {
                this.searchFrom.subsysname = data.subsysname
                this.searchFrom.subsystemid = data.subsystemid
                this.getDeviceList()
            }
        },

        /* 右侧列表操作 */
        // 获取设备数据列表
        async getDeviceList() {
            this.loading = true
            const obj = {
                drmanager: {
                    appid: this.botData.id,
                    drname: this.searchFrom.drname,
                    drtype: null, // Todo?
                    subsystemid: this.searchFrom.subsystemid
                },
                pages: {
                    page: this.pages.page,
                    size: this.pages.size
                }
            }
            try {
                const { data } = await getDeviceList(obj)
                data.records.forEach(item => {
                    if (item.dractivetype) {
                        item.dractivetype = JSON.parse(item.dractivetype)
                    }
                })
                this.tableData = data.records
                this.pages.page = data.current
                this.pages.size = data.size
                this.pages.total = data.total
            } catch (error) {
                console.log(error)
            } finally {
                this.loading = false
            }
        },

        // 重置按钮
        refresh() {
            this.searchFrom.subsysname = null
            this.searchFrom.subsystemid = null
            this.getDeviceList()
        },

        // 添加按钮
        addItemsBtn() {
            if (!this.searchFrom.subsysname) {
                this.$message.warning('请先选着需要添加的类型!')
            } else {
                this.addDialogForm.appid = this.botData.id
                this.addDialogForm.subsystemid = this.searchFrom.subsystemid
                this.addDialogState = 0
                this.dialogTitle = '添加设备信息'
                this.dialogVisible = true
            }
        },

        /* table选择事件 */
        handleSelectionChange(val) {
            let nowArr = []
            console.log(val)
            val.forEach(item => {
                nowArr.push(item.drid)
            })
            this.isCheckedArr = nowArr
        },

        // 批量删除
        async batchRemove() {
            if (this.isCheckedArr.length > 0) {
                this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async() => {
                        if (this.isCheckedArr.length === this.tableData.length) {
                            if (this.pages.page > 1) {
                                this.pages.page--
                            } else {
                                this.pages.page = 1
                            }
                        }
                        const { message } = await deleteDeviceItems(this.isCheckedArr)
                        await this.getDeviceList()
                        this.$message.success({ message })
                    })
                    .catch(error => {
                        console.log(error)
                        this.$refs.table.clearSelection()
                    })
            } else {
                this.$message.warning('请选择需要删除的项目')
            }
        },

        /* 弹出框数据获取 */
        // 特殊类型值获取
        async getSpecialList() {
            const { data } = await getSpecialList()
            this.andorData = data
            this.andorData.unshift({ typename: '未选择', id: 0 })
        },
        // 关联视频数据
        async getVideoList() {
            const { data } = await getVideoList(this.botData.id)
            this.spdridData = data
        },
        // 资产类型数据
        async getAssetsTypeList() {
            const { data } = await getAssetsTypeList(this.botData.id)
            this.assetsData = data
        },
        // 安装位置数据
        async getBYIdAllList() {
            const { data } = await getBYIdAllList(this.botData.id)
            this.drpositionData = data
        },
        /* 弹出框事件 */
        // 关闭
        addDialogClose() {
            this.addDialogForm = {
                drid: null,
                appid: null,
                drname: null,
                subsystemid: null,
                dricon: null,
                drtype: null,
                drno: null,
                assetsid: null,
                drdescribe: null,
                drposition: null,
                dractivetype: [],
                spdrid: null,
                drqrcode: null
            }
            this.dialogTitle = ''
        },
        // 位置选着联想
        querySearch() {},
        // 确定
        async sendAddItem() {
            this.addDialogForm.dractivetype = `[${this.addDialogForm.dractivetype}]`
            if (this.addDialogForm.drposition) {
                this.addDialogForm.drposition = this.addDialogForm.drposition.toString()
            }
            try {
                const { message } = await addDeviceItem(this.addDialogForm)
                this.$message.success(message)
            } catch (error) {
                console.log(error)
            } finally {
                if (this.tableData.length === this.pages.size) {
                    this.pages.page++
                }
                this.dialogVisible = false
                this.getDeviceList()
            }
        },
        // 提交
        async sendEditItem() {
            try {
                const { message } = await editDevicedelete(this.addDialogForm)
                this.$message.success(message)
            } catch (error) {
                console.log(error)
            } finally {
                this.dialogVisible = false
            }
        },

        /* tabel-item 操作 */
        // 编辑
        handleEdit(data) {
            console.log(data)
            this.addDialogForm = { ...data }
            this.addDialogState = 1
            this.dialogTitle = '编辑设备信息'
            this.dialogVisible = true
        },
        // 删除
        handleDetele(data) {
            this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async() => {
                    const { message } = await deleteDeviceItem(data.drid)
                    if (this.tableData.length === 1) {
                        if (this.pages.page > 1) {
                            this.pages.page--
                        } else {
                            this.pages.page = 1
                        }
                    }
                    await this.getDeviceList()
                    this.$message.success({ message })
                })
                .catch(error => {
                    console.log(error)
                })
        },

        /* 分页操作 */
        // 分页当前页切换
        async handleCurrentChange(newPage) {
            this.pages.page = newPage
            this.getDeviceList()
        },
        // 分页显示条数切换
        async handleSizeChange(newSize) {
            this.pages.size = newSize
            this.getDeviceList()
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 15px 20px;
}
::v-deep .el-divider {
    margin: 14px 0 !important;
}

#DeviceManagement {
    .app-container {
        .left {
            .item-box {
                height: calc(100vh - 92px);
                overflow: auto;
                .tree-search {
                    margin-bottom: 10px;
                }
            }
        }
        .right {
            .right-container {
                height: calc(100vh - 92px);
                .search {
                    border: 1px solid #dcdfe6;
                    border-top: none;
                    padding: 34px 10px 10px 10px;
                    margin-top: -14px;
                    .el-input {
                        width: 240px;
                    }
                    .el-button {
                        margin-left: 20px;
                    }
                }
                .btns {
                    padding: 10px 0;
                }
            }
        }
    }
    .add-dialog-container {
        .el-input,
        .el-select,
        .el-autocomplete {
            width: calc(100% - 10px);
        }
        .checkbox {
            padding: 0 15px;
        }
    }
}
</style>
